package com.hgc.ch02.forkjoin;

import com.hgc.ch02.tool.MakeArray;

import java.util.Arrays;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * Created by 01367627 on 2019/7/8.
 */
public class FJSum {

    private static class SubTask extends RecursiveTask<Integer> {

        private int[] src;

        public SubTask(int[] src) {
            this.src = src;
        }

        @Override
        protected Integer compute() {
            if (src.length <= MakeArray.THRESHOLD) {
                return sumArray(src);
            }else{
                int middle = src.length / 2;
                SubTask leftTask = new SubTask(Arrays.copyOfRange(src,0,middle));
                SubTask rightTask = new SubTask(Arrays.copyOfRange(src,middle,src.length));
                invokeAll(leftTask,rightTask);
                return leftTask.join() + rightTask.join();
            }
        }


    }

    private static int sumArray(int[] src) {
        int sum = 0;
        for (int i : src) {
            sum += i;
        }
        return sum;
    }

    public static void main(String[] args) {
        int size = 4000000;
        int[] array = MakeArray.makeArray(4000000);
        ForkJoinPool pool = new ForkJoinPool();
        SubTask mainTask = new SubTask(array);
        long start = System.currentTimeMillis();
        Integer result = pool.invoke(mainTask);
        System.out.println("FJ加总" + size + "数据共花费：" + (System.currentTimeMillis() - start) + "ms,结果为：" + result);
        start = System.currentTimeMillis();
        result = sumArray(array);
        System.out.println("直接加总" + size + "数据共花费：" + (System.currentTimeMillis() - start) + "ms,结果为：" + result);
    }

}
